<template>
  <div class="info" style="margin-top: 15px">
    <a-spin :spinning="spinning">
      <!--表单区    -->
      <div class="form">
        <a-form :label-col="{ span: 4 }" :wrapper-col="{ span: 18 }" layout="vertical">
          <a-row>
            <a-col :span="12">
              <a-form-item label="标识" v-bind="validateInfos.key">
                <a-input v-model:value="modelRef.key" disabled placeholder="请输入角色英文标识" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="名称" v-bind="validateInfos.name">
                <a-input v-model:value="modelRef.name" :disabled="isDetl" placeholder="请输入角色名称" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-item label="表达式" v-bind="validateInfos.action">
                <div style="position: relative">
                  <div style="position: absolute; top: -30px; left: 55px">
                    <a-tooltip>
                      <template #title>例: kuka.*:*</template>
                      <question-circle-outlined />
                    </a-tooltip>
                  </div>
                </div>
                <a-input
                  v-model:value="modelRef.action"
                  :disabled="isDetl"
                  placeholder="请输入表达式"
                  @change="resource.onchangeInput"
                />
                <div style="position: relative">
                  <h6 style="position: absolute; color: #f5222d">{{ resource.validator }}</h6>
                </div>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="分组">
                <a-select
                  v-model:value="selection.value"
                  :options="selection.options"
                  show-search
                  :filter-option="selection.filterOption"
                  :field-names="{ label: 'name', value: 'key' }"
                  mode="multiple"
                  :disabled="isDetl"
                  placeholder="请选择"
                  @change="selection.onchange"
                ></a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-item label="匹配资源">
                <div :class="{ ppzy: 1, ppzy2: !isDetl }">
                  <div v-for="(item, idx) in resource.options" :key="idx">{{ item.key }}</div>
                </div>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-item label="备注" v-bind="validateInfos.describe">
                <a-textarea
                  v-model:value="modelRef.describe"
                  placeholder="备注"
                  :disabled="isDetl"
                  :auto-size="{ minRows: 2, maxRows: 2 }"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-spin>
    <!--页脚按钮    -->
    <div class="=foot">
      <a-space v-if="isDetl" :size="8">
        <a-button @click="enterEdit">进入编辑</a-button>
      </a-space>
      <a-space v-else :size="8">
        <a-button type="primary" @click="onSubmit">保存</a-button>
        <a-button @click="onReset">重置</a-button>
      </a-space>
    </div>
  </div>
</template>

<script setup>
import { defineComponent, toRaw, ref, watch, defineEmits, toRefs, inject, reactive, nextTick } from 'vue'
import { QuestionCircleOutlined } from '@ant-design/icons-vue'
import { Form } from 'ant-design-vue'
import factory from '@/views/permission-manag/factory'
import exp from '@/utils/regular'
import { message } from 'ant-design-vue'

const { currentItemId } = inject('roleParams')

const useForm = Form.useForm
const modelRef = reactive({
  key: '',
  name: '',
  action: '',
  groupList: [],
  describe: '',
})

//==重置==================================
const backupData = {}
const onReset = () => {
  for (let key in backupData) {
    modelRef[key] = JSON.parse(JSON.stringify(backupData[key]))
  }
  selection.value = []
  for (let key in modelRef['groupList']) {
    selection.value.push(key)
  }
}
//==回显数据=========================================
const spinning = ref(true)
const getPermisDetial = () => {
  factory.getPermisDetial({ key: currentItemId.value.key }).then((res) => {
    spinning.value = false
    for (let key in res.data) {
      modelRef[key] = res.data[key]
      backupData[key] = JSON.parse(JSON.stringify(res.data[key]))
      if (key === 'action') {
        resource.getResourcesForExp(modelRef[key])
      }
    }
    selection.getPermisGroup()
  })
}
getPermisDetial()

//==表单验证,保存====================================================
const rulesRef = reactive({
  name: [
    {
      required: true,
      message: '请输入名称',
    },
    {
      pattern: exp.name.pattern,
      message: exp.name.message,
    },
  ],
  key: [
    {
      required: true,
      message: '请输入英文标识',
    },
    {
      pattern: exp.key.pattern,
      message: exp.key.message,
    },
  ],
  action: [
    {
      required: true,
      message: '请输入表达式',
    },
  ],
  describe: [
    {
      max: 127,
      message: '最多输入127个字符',
    },
  ],
})
const { validate, validateInfos } = useForm(modelRef, rulesRef, {
  //表单验证的输出: 字段 值 提示
  onValidate: (...args) => {
    console.log('表单验证的输出: 字段 值 提示', ...args)
  },
})
const emit = defineEmits(['update-success'])
const onSubmit = () => {
  validate()
    .then(() => {
      //表单验证无误后执行
      modelRef.groupList = selection.value
      factory.updatePermis(modelRef).then((res) => {
        message.success('保存成功!')
        emit('update-success', '')
        quiteEdit()
      })
    })
    .catch((err) => {
      console.log('error', err)
    })
}

//==资源=====================================
const resource = reactive({
  options: [],
  validator: '',
  timerOnChange: null,
  onchangeInput: (val) => {
    clearTimeout(resource.timerOnChange)
    if (val.target.value) {
      resource.timerOnChange = setTimeout(() => {
        resource.validator = ''
        resource.options = []
        resource.getResourcesForExp(val.target.value)
      }, 1000)
    } else {
      resource.validator = ''
    }
  },
  getResourcesForExp: (action = '') => {
    factory
      .getResourcesForExp({ action })
      .then((res) => {
        resource.options = res.data
        resource.validator = resource.options.length ? '' : '表达式没有匹配到资源'
      })
      .catch((err) => {
        resource.validator = err.response.data.message
      })
  },
})

//==分组 选择器========================================
const selection = reactive({
  value: [],
  options: [],
  filterOption: (input, option) => {
    return option.name.toLowerCase().indexOf(input.toLowerCase()) >= 0
  },
  //获得权限分组
  getPermisGroup: (search = '') => {
    factory.getPermisGroup({ search }).then((res) => {
      res.data.forEach((item) => {
        selection.options.push(item)
      })
      for (let key in modelRef['groupList']) {
        selection.value.push(key)
      }
    })
  },
})

//==进入编辑============================
const isDetl = ref(true)
const enterEdit = () => {
  isDetl.value = false
}
const quiteEdit = () => {
  isDetl.value = true
}
</script>

<style scoped>
.ppzy {
  width: 100%;
  height: 100px;
  overflow: auto;
  background-color: #f5f5f5;
  border: 1px solid #d9d9d9;
}

.ppzy2 {
  background-color: white;
}
</style>
